package com.zrzy.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zrzy.beans.PageBean;
import com.zrzy.entity.User;
import com.zrzy.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/")
public class UserController {
    @Resource
    private UserService userService;

    /**
     * 登录界面
     *
     * @return 模板文件名
     */
    @RequestMapping(value = "login.html")
    public String loginUrl() {
        return "login";
    }

    /**
     * 管理主页界面
     *
     * @return 模板文件名
     */
    @RequestMapping(value = "home.html")
    public String homeUrl() {
        return "home";
    }


    /**
     * 登录失败界面
     *
     * @return 模板文件名
     */
    @RequestMapping(value = "fail.html")
    public String failUrl() {
        return "fail";
    }

    /**
     * 用户列表界面
     *
     * @return 模板文件名
     */
    @RequestMapping(value = "user/list.html")
    public String userListUrl() {
        return "userList";
    }


    /**
     * 判断用户名是否存在接口(Restful)
     *
     * @param username 用户名
     * @return JSON 数据
     */
    @ResponseBody
    @RequestMapping(value = "user/existence/{username}", produces = "application/json")
    public String existUsername(@PathVariable String username) {
        JSONObject result = new JSONObject();
        int verify = userService.verify(username, "");
        result.put("status", verify);
        return result.toJSONString();
    }

    /**
     * 用户登录
     *
     * @param body    请求正文
     * @param session HttpSession
     * @return 响应正文
     */
    @ResponseBody
    @RequestMapping(value = "user/doLogin", method = RequestMethod.POST, produces = "application/json")
    public String doLogin(@RequestBody User body, HttpSession session) {
        String username = body.getUsername();
        String password = body.getPassword();
        JSONObject result = new JSONObject();
        int verify = userService.verify(username, password);
        if (verify == UserService.LOGIN_SUCCESS) {
            User user = userService.login(username, password);
            session.setAttribute("USER", user);
            // TODO: 2017/3/3 0003 0:03 更新用户登录时
            userService.updateLoginTime(user.getUserId());
            result.put("url", "home.html");
        }
        result.put("status", verify);
        return result.toJSONString();
    }

    /**
     * 用户注销
     *
     * @param session HttpSession
     * @return 页面地址
     */
    @RequestMapping(value = "user/doLogout")
    public String doLogout(HttpSession session) {
        session.removeAttribute("USER");
        session.invalidate();
        return "redirect:/login.html";
    }


    @ResponseBody
    @RequestMapping(value = "user/list.json", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json;charset=UTF-8")
    public String listUserByPage(@RequestParam(value = "p", required = false, defaultValue = "1") int pageNumber,
                                 @RequestParam(value = "s", required = false, defaultValue = "5") int pageSize) {
        PageBean<User> userPageBean = userService.queryForPage(pageNumber, pageSize);
        return JSON.toJSONString(userPageBean);
    }


    @RequestMapping(value = "user/listAll.html")
    public ModelAndView index() {
        ModelAndView mv = new ModelAndView("listAllUser");
        List<User> all = userService.getAll();
        mv.addObject("title", "用户列表");
        mv.addObject("users", all);
        return mv;
    }

    /**
     * 方法一：原生响应 JSON 数据的方法
     *
     * @param request  请求
     * @param response 响应
     */
    @RequestMapping(value = "getJson/listAll")
    public void getJson(HttpServletRequest request, HttpServletResponse response) {
        // TODO: 2017/3/2 10:06 通过 request 处理返回业务数据 省略……
        //将业务数数据置入 JSONObject 对象中
        List<User> users = userService.getAll();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("users", users);
        //设置响应的字符编码，可以使用过滤器
//        response.setCharacterEncoding("UTF-8");
        //设置响应结果的类型为 json，浏览器显示编码格式 UTF-8
        response.setContentType("application/json;charset=UTF-8");
//        response.setContentType("text/html;charset=UTF-8");
        //输出 JSON 对象数据
        try {
            response.getWriter().write(jsonObject.toJSONString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 方法二：@ResponseBody 注解 响应 JSON 数据(将返回值放入响应体中)
     *
     * @return 返回的结果内容
     */
    @RequestMapping(value = "getJson/listAll2")
    @ResponseBody
    public Map<String, Object> getJson() {
        Map<String, Object> map = new HashMap<>();
        List<User> users = userService.getAll();
        map.put("users", users);
        map.put("name", "中软国际");
        map.put("age", "28");
        return map;
    }
}
